
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' as intl;
import 'package:xim/widget/dash_chat_2/dash_chat_2.dart';

/// 消息时间提示展示组件
class DateSeparator extends StatelessWidget {
  const DateSeparator({
    required this.date,
    this.messageListOptions = const MessageListOptions(),
    this.padding = const EdgeInsets.symmetric(vertical: 20),
    this.textStyle = const TextStyle(color: Colors.grey),
    Key? key,
  }) : super(key: key);

  /// Date to show
  final DateTime date;

  /// Options to customize the behaviour and design of the overall list of message
  final MessageListOptions messageListOptions;

  /// Padding of the separator
  final EdgeInsets padding;

  /// Style of the text
  final TextStyle textStyle;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: padding,
      child: Text(
        _formatDateSeparator(date),
        style: textStyle,
      ),
    );
  }

  String _formatDateSeparator(DateTime date) {
    if (messageListOptions.dateSeparatorFormat != null) {
      return messageListOptions.dateSeparatorFormat!.format(date);
    }

    final DateTime today = DateTime.now();

    if (date.year != today.year) {
      return intl.DateFormat('yyyy年MM月dd日 HH:mm').format(date);
    } else if (date.month != today.month || _getWeekOfYear(date) != _getWeekOfYear(today)) {
      return intl.DateFormat('MM月dd日 HH:mm').format(date);
    } else if (date.day != today.day) {
      if(today.day - date.day == 1){
        return intl.DateFormat('昨天 HH:mm').format(date);
      }
      return intl.DateFormat('星期${toWeekNumber(date.weekday)} HH:mm').format(date);
    }
    return intl.DateFormat('HH:mm').format(date);
  }

  int _getWeekOfYear(DateTime date) {
    final int dayOfYear = int.parse(intl.DateFormat('D').format(date));
    return ((dayOfYear - date.weekday + 10) / 7).floor();
  }

  String toWeekNumber(int i){
    switch(i){
      case 1: return "一";
      case 2: return "二";
      case 3: return "三";
      case 4: return "四";
      case 5: return "五";
      case 6: return "六";
      case 7: return "日";
      default:
        return "";
    }
  }
}
